﻿using CompanyManageSystem.DLL;
using CompanyManageSystem.Model;
using CompanyManageSystem.Service;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace CompanyManageSystem.UI.Info
{
    public partial class Frm_Supplier : BaseXtraForm
    {
        #region 属性
        //图片字节二维数组
        public byte[][] PByte = new byte[5][];

        //PictureList控件列
        List<PictureEdit> pEdit;
        #endregion

        public Frm_Supplier()
        {
            InitializeComponent();
            this.BindRowIndicator(SupplierView);
            this.BindCheckEdit(SupplierView, false, false);
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Supplier_Load(object sender, EventArgs e)
        {
            RepastService aservice = new RepastService();
            treeList1.DataSource = aservice.GetAllSupplierCategory();

            //只读
            SetOnlyRead();

            #region TreeList属性
            treeList1.OptionsView.ShowColumns = false;
            treeList1.LookAndFeel.UseWindowsXPTheme = true;
            treeList1.LookAndFeel.UseDefaultLookAndFeel = false;
            treeList1.OptionsView.ShowVertLines = false;
            treeList1.OptionsView.ShowHorzLines = false;
            treeList1.Appearance.FocusedCell.BackColor = Color.LightSteelBlue;
            treeList1.Appearance.FocusedCell.BackColor2 = Color.SteelBlue;
            treeList1.OptionsView.FocusRectStyle = DevExpress.XtraTreeList.DrawFocusRectStyle.None;
            #endregion
        }

        /// <summary>
        /// 设置为只读
        /// </summary>
        public void SetOnlyRead()
        {
            this.CodeEdit.Properties.ReadOnly = true;
            this.NameEdit.Properties.ReadOnly = true;
            this.ContactEdit.Properties.ReadOnly = true;
            this.PhoneEdit.Properties.ReadOnly = true;
            this.AddressEdit.Properties.ReadOnly = true;
            this.CategoryEdit.Properties.ReadOnly = true;
            this.CreateTime.Properties.ReadOnly = true;
        }

        /// <summary>
        /// 右键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                popupMenu1.ShowPopup(Control.MousePosition);
            }
        }

        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var categoryID = treeList1.FocusedNode.GetValue("ID");

            Frm_AddSupplier frm = new Frm_AddSupplier(id: (Guid)categoryID, status: EStatus.Add);
            frm.SaveEvent += supplier_AddSaveEvent;
            frm.ShowDialog();
        }
        private void supplier_AddSaveEvent(Object sender, EventArgs e)
        {
            RepastService aservice = new RepastService();
            var focusCategoryID = treeList1.FocusedNode.GetValue("ID");
            SupplierGrid.DataSource = aservice.GetSupplierByCategoryID((Guid)focusCategoryID);

            SetInfoAfterFocusNodeChanged();
        }

        /// <summary>
        /// 编辑供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var supplier = SupplierView.GetFocusedRow() as Supplier;
            if (supplier == null)
            {
                ShowInfo("请选择供应商!");
                return;
            }
            Frm_AddSupplier frm = new Frm_AddSupplier(id: supplier.ID, status: EStatus.Modify);
            frm.SaveEvent += supplier_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void supplier_UpdateSaveEvent(Object sender, EventArgs e)
        {
            var focusCategoryID = treeList1.FocusedNode.GetValue("ID");
            var supplier = sender as Supplier;
            if (supplier != null)
            {
                SupplierView.SetFocusedRowCellValue("Code", supplier.Code);
                SupplierView.SetFocusedRowCellValue("Name", supplier.Name);
                SupplierView.SetFocusedRowCellValue("Address", supplier.Address);
                SupplierView.SetFocusedRowCellValue("Contracts", supplier.Contracts);
                SupplierView.SetFocusedRowCellValue("Phone", supplier.Phone);

                SetInfoAfterFocusNodeChanged();
            }
            else
            {
                RepastService aservice = new RepastService();
                SupplierGrid.DataSource = aservice.GetSupplierByCategoryID((Guid)focusCategoryID);

                SetInfoAfterFocusNodeChanged();
            }
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RepastService aservice = new RepastService();

            //获取分类焦点行ID
            var focusCategoryID = treeList1.FocusedNode.GetValue("ID");

            var supplier = this.GetChecked<Supplier>(SupplierView);

            if (supplier.Count == 0)
            {
                ShowInfo("请选择需要删除的供应商!");
                return;
            }

            //将流写入Guid数组
            var supplierID = supplier.Select(p => p.ID).ToArray();
            if(ShowQuestion("是否删除所选供应商?"))
            {
                int count = aservice.DelSupplierByCheckedID((Guid)focusCategoryID, supplierID);
                aservice.DelSupplierpictureByCheck(supplierID);
                SetInfoAfterFocusNodeChanged();
                SupplierGrid.DataSource = aservice.GetSupplierByCategoryID((Guid)focusCategoryID);
            }

        }

        /// <summary>
        /// TreeList焦点行改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            RepastService rservice = new RepastService();
            var focusCategoryID = treeList1.FocusedNode.GetValue("ID");
            SupplierGrid.DataSource = rservice.GetSupplierByCategoryID((Guid)focusCategoryID);

            SetInfoAfterFocusNodeChanged();
        }

        /// <summary>
        /// SupplierView焦点行改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SupplierView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            SetInfoAfterFocusNodeChanged();
        }

        /// <summary>
        /// TreeList和GridControl焦点行改变后设置信息
        /// </summary>
        public void SetInfoAfterFocusNodeChanged()
        {
            var rservice = new RepastService();
            var supplier = this.SupplierView.GetFocusedRow() as Supplier;
            var category = this.treeList1.FocusedNode.GetValue("Name");

            //设置信息
            if (supplier != null)
            {
                //文本
                SetInfo(supplier.Code, supplier.Name, (string)category, supplier.Contracts, supplier.Phone, supplier.Address, supplier.EnterTime);

                //图片
                pEdit = new List<PictureEdit> { pictureEdit1, pictureEdit2, pictureEdit3, pictureEdit4, pictureEdit5 };
                var pic = rservice.GetSupplierPicture(supplier.ID);
                for (int i = 0; i < pEdit.Count; i++)
                {
                    if (i >= pic.Count)
                    {
                        pEdit[i].EditValue = null;
                    }
                    else
                    {
                        pEdit[i].EditValue = ChangePictureSize(pic[i]);
                    }
                }
            }
            else
            {
                //信息框设置为空
                SetInfo("", "", "", "", "", "", DateTime.Now);
                //PictureEdit设置为null
                pEdit = new List<PictureEdit> {pictureEdit1,pictureEdit2, pictureEdit3, pictureEdit4, pictureEdit5 };
                foreach (var item in pEdit)
                {
                    item.EditValue = null;
                }
            }
        }

        /// <summary>
        /// 设置文本信息
        /// </summary>
        public void SetInfo(string code, string name, string category, string contact, string phone, string address, DateTime createTime)
        {
            CodeEdit.Text = code;
            NameEdit.Text = name;
            CategoryEdit.Text = category;
            ContactEdit.Text = contact;
            PhoneEdit.Text = phone;
            AddressEdit.Text = address;
            CreateTime.DateTime = createTime;
        }

        /// <summary>
        /// 改变图片大小方法
        /// </summary>
        public byte[] ChangePictureSize(byte[] data)
        {
            //从流中获取字节
            var img = Image.FromStream(new MemoryStream(data));
            var newimg = new Bitmap(img, new Size(pictureEdit1.Width, pictureEdit1.Height));
            //创建新流
            var ms = new MemoryStream();
            //将图片保存到新流中，并设置格式
            newimg.Save(ms, ImageFormat.Jpeg);
            //将流内容写入字节数组
            return ms.ToArray();
        }

        /// <summary>
        /// 数字转中文
        /// </summary>
        /// <param name="LowerMoney"></param>
        /// <returns></returns>
        public string MoneyToChinese(string LowerMoney)
        {
            string functionReturnValue = null; bool IsNegative = false; // 是否是负数     
            if (LowerMoney.Trim().Substring(0, 1) == "-")
            {       // 是负数则先转为正数       
                LowerMoney = LowerMoney.Trim().Remove(0, 1); IsNegative = true;
            }
            string strLower = null;
            string strUpart = null;
            string strUpper = null;
            int iTemp = 0;     // 保留两位小数 123.489→123.49　　123.4→123.4     
            LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
            if (LowerMoney.IndexOf(".") > 0)
            {
                if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
                {
                    LowerMoney = LowerMoney + "0";
                }
            }
            else
            {
                LowerMoney = LowerMoney + ".00";
            }
            strLower = LowerMoney;
            iTemp = 1;
            strUpper = "";
            while (iTemp <= strLower.Length)
            {
                switch (strLower.Substring(strLower.Length - iTemp, 1))
                {
                    case ".": strUpart = "圆"; break;
                    case "0": strUpart = "零"; break;
                    case "1": strUpart = "壹"; break;
                    case "2": strUpart = "贰"; break;
                    case "3": strUpart = "叁"; break;
                    case "4": strUpart = "肆"; break;
                    case "5": strUpart = "伍"; break;
                    case "6": strUpart = "陆"; break;
                    case "7": strUpart = "柒"; break;
                    case "8": strUpart = "捌"; break;
                    case "9": strUpart = "玖"; break;
                }
                switch (iTemp)
                {
                    case 1: strUpart = strUpart + "分"; break;
                    case 2: strUpart = strUpart + "角"; break;
                    case 3: strUpart = strUpart + ""; break;
                    case 4: strUpart = strUpart + ""; break;
                    case 5: strUpart = strUpart + "拾"; break;
                    case 6: strUpart = strUpart + "佰"; break;
                    case 7: strUpart = strUpart + "仟"; break;
                    case 8: strUpart = strUpart + "万"; break;
                    case 9: strUpart = strUpart + "拾"; break;
                    case 10: strUpart = strUpart + "佰"; break;
                    case 11: strUpart = strUpart + "仟"; break;
                    case 12: strUpart = strUpart + "亿"; break;
                    case 13: strUpart = strUpart + "拾"; break;
                    case 14: strUpart = strUpart + "佰"; break;
                    case 15: strUpart = strUpart + "仟"; break;
                    case 16: strUpart = strUpart + "万"; break;
                    default: strUpart = strUpart + ""; break;
                }
                strUpper = strUpart + strUpper;
                iTemp = iTemp + 1;
            }
            strUpper = strUpper.Replace("零拾", "零");
            strUpper = strUpper.Replace("零佰", "零");
            strUpper = strUpper.Replace("零仟", "零");
            strUpper = strUpper.Replace("零零零", "零");
            strUpper = strUpper.Replace("零零", "零");
            strUpper = strUpper.Replace("零角零分", "整");
            strUpper = strUpper.Replace("零分", "整");
            strUpper = strUpper.Replace("零角", "零");
            strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("零亿零万", "亿");
            strUpper = strUpper.Replace("零万零圆", "万圆");
            strUpper = strUpper.Replace("零亿", "亿");
            strUpper = strUpper.Replace("零万", "万");
            strUpper = strUpper.Replace("零圆", "圆");
            strUpper = strUpper.Replace("零零", "零");
            // 对壹圆以下的金额的处理     
            if (strUpper.Substring(0, 1) == "圆") { strUpper = strUpper.Substring(1, strUpper.Length - 1); }
            if (strUpper.Substring(0, 1) == "零") { strUpper = strUpper.Substring(1, strUpper.Length - 1); }
            if (strUpper.Substring(0, 1) == "角") { strUpper = strUpper.Substring(1, strUpper.Length - 1); }
            if (strUpper.Substring(0, 1) == "分") { strUpper = strUpper.Substring(1, strUpper.Length - 1); }
            if (strUpper.Substring(0, 1) == "整") { strUpper = "零圆整"; }
            functionReturnValue = strUpper;
            if (IsNegative == true)
            {
                return "负" + functionReturnValue;
            }
            else
            {
                return functionReturnValue;
            }
        }

        
    }
}

